const
  base = require('./api/base'),
  utils = require('./utils/util');

App({
  onLaunch(options) {
    //设备号
    let uuid = wx.getStorageSync('uuid'),
      uid = wx.getStorageSync('uid'),
      systemInfo = wx.getSystemInfoSync();

    //无设备号则生成设备号
    if (!uuid) {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";

      uuid = s.join("");

      wx.setStorageSync('uuid', uuid);
      // wx.setStorageSync('token', '');
    }
    //是否是测试版
    // this.globalData.isDev=true
    //启动参数
    this.globalData.launchOptions = options;
    //启动参数
    console.log('启动参数', options);
    //神策
    // this.sensors = sa;
    //设备号
    this.globalData.uuid = uuid;
    //token
    // this.globalData.authToken = wx.getStorageSync('token');
    //用户信息
    this.globalData.userInfo = wx.getStorageSync('userinfo');
    // sessionID
    this.globalData.ssId = wx.getStorageSync('ssId');
    //设备信息
    this.globalData.SystemInfo = systemInfo;
    //是否为iPhone X
    this.globalData.isIpx = systemInfo.model.search('iPhone X') !== -1;
    //监听网络状态
    this.watchingNetwork();
    // 购物车信息
    this.globalData.cart = wx.getStorageSync('cart');
    //获取用户状态
    // this.getUserStatus();
    //获取用户openid
    // this.getOpenid();
  },

  /**
   * 获取公用的请求头
   */
  getHeader() {
    let gbd = this.globalData,
      sys = gbd.SystemInfo || {},
      ui = gbd.userInfo || {},
      loc = gbd.location || {};
    return {
      // "Authorization": gbd.authToken || '',
      "SDKVersion": sys.SDKVersion || '',
      "userId": ui.userId || '',
      "DeviceBrand": sys.brand || '',
      "DevicePlatform": sys.platform || '',
      "DeviceModel": sys.model || '',
      "DeviceSystem": sys.system || '',
      "DeviceVersion": sys.version || '',
      "UserLongitude": loc.longitude || '',
      "UserLatitude": loc.latitude || '',
      "RequsetSource": 'wx',
    }
  },

  /**
   * 自定义导航栏UI数据
   */
  customNav() {
    let info = { width: 87, height: 32, left: 278, top: 26, right: 365, bottom: 58 },
      sysInfo = this.globalData.SystemInfo,
      pb = 10; //自定义导航下边距

    try {
      info = wx.getMenuButtonBoundingClientRect(); //导航胶囊按钮UI数据
    } catch (e) {
      base.errorLog.call(this, '获取导航栏数据失败: ' + JSON.stringify(e)).catch(e => {
        console.error('上报日志失败', e);
      });
    }

    this.globalData.nav = { //以下均以px为单位
      height: info.height,
      paddingTop: info.top,
      paddingBottom: pb,
      paddingLeft: 10,
      boxHeight: info.top + info.height + pb - 1, // -1是因为Android手机上sticky定位的元素与标题会有1像素的间隙
      width: info.width,
      paddingRight: sysInfo.windowWidth - info.right,
    };
  },

  /**
   * 监听网络状态变化
   */
  watchingNetwork() {
    try {
      let _this = this,
        handler = res => {
          let pages = getCurrentPages(),
            page = pages[pages.length - 1],
            route = page ? page.route : '';

          if (res.networkType === "none") {
            wx.showModal({
              title: 'oops!',
              content: '网络似乎断了...',
              showCancel: false,
              confirmColor: '#FF6366',
            });
          }
          //从无网断状态变为有网
          else if (_this.netState === 'none') {
            //当前页面为视频直播页面,重连
            if (route === 'sub_third/pages/live/room/room') page.reconnect();
            if (page.reload) page.reload()
          }

          //记录网络状态
          _this.netState = res.networkType;
          this.globalData.networkType = res.networkType;
        };

      wx.getNetworkType({ success: handler });
      wx.onNetworkStatusChange(handler);
    } catch (e) {
      console.log('watchingNetwork error', e);
    }
  },

  //获取版本更新
  getVersionUpdate() {
    const updateManager = wx.getUpdateManager();

    updateManager.onCheckForUpdate((res) => {
      // 请求完新版本信息的回调
      console.log('有无版本更新', res.hasUpdate);
    });

    updateManager.onUpdateReady(() => {
      wx.showModal({
        title: '更新提示',
        cancelColor: '#FF6366',
        confirmColor: '#000000',
        content: '新版本已经准备好，为了更好的体验，是否重启应用？',
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    });

    updateManager.onUpdateFailed((e) => {
      console.log('获取版本更新失败', e);
    });
  },

  //页面404
  onPageNotFound(res) {
    console.log('页面未找到', res);
  },

  //app show
  onShow() {
    //获取版本更新
    this.getVersionUpdate();
    //获取本地时间与服务器时间的time diff
    // this.getTimeDiff();
    //小程序切换前台(用于crm通知咨询师,用户打开了小程序)
    // this.appShowMessage();

    // this.getUserStatus();
  },

  //获取用户状态
  async getUserStatus() {
    let userId = this.globalData.userInfo.userId;

    if (userId) {
      try {
        let res = await base.getUserStatus.call(this, userId),
          data = res.data.data || {};
        //用户被禁用
        if (!data.userIsEnable) {
          wx.showModal({
            title: '账号异常',
            confirmColor: '#000000',
            content: '账号异常，登陆失败',
            showCancel: false,
            success() {
              utils.signOut();
            }
          })
        }
      } catch (e) {
        console.error('获取用户状态失败', e)
      }
    }
  },

  //获取用户openid
  async getOpenid() {
    let _this = this,
      openid = '';

    wx.login({
      async complete(e) {
        let code = e.code || '';

        //微信登录成功,有code
        if (code) {
          try {
            let res = await base.wxOnLogin.call(_this, { code });
            console.log(res, 'openid res')
            openid = res.data.data || '';
            _this.globalData.openid = openid;
          } catch (e) {
            console.error('获取openid失败', e);
          }
        }
      }
    });
  },

  //globalData中不应该存放生命周期内可变的用户数据
  //否则可能导致数据更新延迟
  globalData: {
    isIpx: false, //是否为iPhone X
    isDev: false, //是否是测试环境
    version: '1.1.17', //小程序版本号
    timeDiff: 0, //本地时间与服务器时间差值
    exp: {
      phone: /^1[3456789]\d{9}$/, //手机号
      idCard: /^\d{17}[\dX]$/, //身份证号
      wxNumber: /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/, //微信号
    },

    /**share(仅在新用户注册时有用)
     *
     * scene: 场景数据
     * 逻辑为：scene存在，且能正常解析出咨询师id(crmuser)，则将新用户分配到该咨询师名下
     * (该场景对应新用户扫码咨询师场景二维码进入小程序并注册)
     *
     * crmuser: 咨询师id
     * 逻辑为： scene不存在，将新用户分配到crmuser对应的咨询师名下
     * (该场景对应新用户扫描用户分享的带'customerId'的小程序卡片进入小程序并注册)
     **/
    share: { //分享数据
      scene: null, //场景数据
      // spread: 12, //渠道
      spreadId: 0, //推广码id
      // crmuser: '',  //顾问
    },
    imageBaseUri: "https://xhbehappy.cn",
    pictureRouting:'http://tntb.westts.cn/memeberStatic/',//迭代图片路由
    defautlImg: "https://xhbehappy.cn/images/tntb_logo.png",
    avatarDefault: { //默认头像
      consultant: 'https://xhbehappy.cn/images/tntb_logo.png',
      hospital: '',
    },
    homeUri: '/pages/index/index', //小程序首页
    authToken: void 0, //token
    SystemInfo: {}, //设备信息
    location: { //定位信息
      longitude: 0,
      latitude: 0,
      updateTime: '',
    },
    launchOptions: null, //启动参数
    uuid: void 0, //模拟设备id
    imID: void 0, // IM 用户ID
    userInfo: { //用户信息
      headImage: void 0,
      nickname: void 0,
      mobile: void 0,
      userId: void 0
    },
    adviser: {}, //咨询师信息
    returnUrl: '', //从分享卡片进入后储存（登录后将跳转至该分享页面）
    webviewUri: void 0, //
    cart: []
  }
})